const path = require('path')
const md5 = require('md5')
const fs = require('fs');
const {promisify} = require('util');
const query = require('../model/query.js')
let CryptoJS = require('crypto-js')

const UserController = {};
const {
    password_secret
} = require('../config/config.js')
const rename = promisify(fs.rename)
UserController.userLogin = async (req, res) => {
    let {
        username,
        password
    } = req.body;
    password = md5(`${password}${password_secret}`)
    const sql = `select * from users where username = '${username}' and password = '${password}'`
    const result = await query(sql)
    if (result.length > 0) {
        req.session.userInfo = result[0];
        res.cookie('userInfo', JSON.stringify(result[0]), {
            expires: new Date(Date.now() + 1 * 3600000),
        })
        res.json({
            code: 0,
            message: "登录成功"
        })
    } else {
        res.json({
            code: -2,
            message: "登录失败"
        })
    }

}
UserController.avatar = async(req,res)=>{
    const {id} = req.session.userInfo;
    let photo = '';
    if (req.file) {
        let {
            destination,
            originalname,
            filename
        } = req.file;
        let extName = originalname.substring(originalname.lastIndexOf('.'))
        let uploadDir = './uploads'
        let oldName = path.join(uploadDir, filename);
        let newName = path.join(uploadDir, filename) + extName;

        try {
            const result = await rename(oldName, newName)
            photo = `uploads/${filename}${extName}`
            let oldAvatar = req.session.userInfo.avatar;
            oldAvatar = path.join(path.dirname(__dirname), oldAvatar)
            fs.unlink(oldAvatar, (err) => {})
        } catch (err) {
            console.log('上传失败')
        }
        const sql = `update users set avatar = '${photo}' where id = ${id}`
        await query(sql)
        const sql2 = `select * from users where id = ${id}`
        const result = await query(sql2)
        req.session.userInfo = result[0];
        res.cookie('userInfo', JSON.stringify(result[0]), {
            expires: new Date(Date.now() + 1 * 3600000),
        })
        res.json({
            code: 0,
            message: "上传成功"
        })
    } else {
        res.json({
            code: -6,
            message: "上传失败",

        })
    }
}
UserController.userLogout = async (req, res) => {
    req.session.destroy(function (err) {
        if (err) {
            throw err;
        }
    })
    res.json({
        code: 0,
        message: "退出成功"
    })

}

UserController.updUserInfo = async (req, res) => {
    const {
        id,
        intro
    } = req.body;
    const sql = `update users set intro = '${intro}' where id = ${id}`;
    const {
        affectedRows
    } = await query(sql)
    const successData = {
        code: 0,
        message: "更新成功，祝您生活愉快"
    }
    const failData = {
        code: -5,
        message: "更新失败，请重新更新"
    }

    if (affectedRows > 0) {
        const sql = `select * from users where id = ${id}`
        const result = await query(sql)
        req.session.userInfo = result[0];
        res.cookie('userInfo', JSON.stringify(result[0]), {
            expires: new Date(Date.now() + 1 * 3600000),
        })

        res.json(successData)
    } else {
        res.json(failData)
    }
}
//更新密码
UserController.updatePassword = (req,res) => {
    let {oldpwd,newpwd,renewpwd} = req.body;
    // 1 校验原密码是否一致
    // let {id} = JSON.parse( req.session.userInfo )
    const {id} = req.session.userInfo;
    let sql = `select password from users where id = ${id}`

    query(sql).then(result=>{
        if(result.length){
            oldpwd = CryptoJS.MD5(`${oldpwd}${password_secret}`).toString();
            if( result[0].password !== oldpwd ){
                // 2 原密码输入错误
                res.json({
                    code: -1,
                    message: "原密码输入错误"
                })
            }else{
                //  2 原密码一致才更新新密码
                newpwd = CryptoJS.MD5(`${newpwd}${password_secret}`).toString();
                let sql = `update users set password = '${newpwd}' where id = ${id}`
                return query(sql);
               
            }
        }
    }).then(result=>{
        if(result.affectedRows){
            res.json({
                code:20000,
                message: '更新密码成功'
            })
        }else{
            res.json({
                code:-2,
                message: '服务器繁忙，请稍后再试'
            })
        }
    })
   
    
}

module.exports = UserController;